package org.shzhyun.opencv;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

import lombok.extern.slf4j.Slf4j;
import org.shzhyun.TtsService;
import org.shzhyun.tools.SoundPlay;
import org.shzhyun.tts.DataUtils;

import ai.djl.Device;
import ai.djl.ndarray.NDManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 1、目前只支持 biaobei这源声
 * 2、因为java的一下基础算和python的结果有区别，所以效果不稳定。
 * 3、有兴趣的可以改进,麻雀虽小五脏俱全
 * @author shiqianghh
 * 本项目仿照ttskit
 */
@Slf4j
@Component
public class OpenCvTTsUtil implements TtsService {

	@Value("${tts.filePath}")
	private String ttsfilePath;
	@Value("${tts.sys}")
	private String ttsSys;
	@Autowired
	private DataUtils dataUtils;

//	public static void main(String[] args) throws Exception {
//		 //被克隆的声音
//		  //Path imageFile = Paths.get("src/main/resources/voice/biaobei-biaobei-009502.mp3");
//		  Path imageFile = Paths.get("C:/gds/szyptp/zim/org.shzhyun.zim/org.shzhyun.tts/ttsfile/voice/biaobei-biaobei-009502.mp3");
//		  //语音保存路径
//		  File outs = new File(Paths.get("build/output")+"/02.wav");
//		  //设置为pytorch引擎
//		  System.setProperty("ai.djl.default_engine", "PyTorch");
//		  NDManager manager = NDManager.newBaseManager(Device.cpu());
//		  DataUtils dataUtils = new DataUtils("C:/gds/ptmodule");
//		  dataUtils.tts(imageFile.toString(),"啤酒饮料八宝粥,瓜子泡面花生米",outs,manager);
//
//		  manager.close();
//		  SoundPlay sound = new SoundPlay(outs);
//	      sound.play();
//	}
	@Override
	public String doTranse(String text){
		System.out.println("1");
		if(Objects.equals("win",ttsSys)){
			System.load(ttsfilePath+"/dll/libwebrtcvadwrapper.dll");
			System.load(ttsfilePath+"/dll/libfvad.dll");
		}else {
			System.load(ttsfilePath+"/so/libfvad.so");
			System.load(ttsfilePath+"/so/libwebrtcvadwrapper.so");
		}
		//被克隆的声音
		System.out.println("2");
		//Path imageFile = Paths.get("src/main/resources/voice/biaobei-biaobei-009502.mp3");
		Path imageFile = Paths.get(ttsfilePath+"/voice/biaobei-biaobei-009502.mp3");
		//语音保存路径
		String name = System.currentTimeMillis()+"";
		File outs = new File(ttsfilePath+"/output/"+name+".wav");
		System.out.println("3");
		//设置为pytorch引擎
		System.setProperty("ai.djl.default_engine", "PyTorch");
		NDManager manager = NDManager.newBaseManager(Device.cpu());

		System.out.println("4");
//		DataUtils dataUtils = new DataUtils(modulePath);
		System.out.println("5");
        try {
            dataUtils.tts(imageFile.toString(),text,outs,manager);
			System.out.println("6");
			manager.close();
			System.out.println("7");
			SoundPlay sound = new SoundPlay(outs);
			System.out.println("8");
			sound.play();
			System.out.println("9");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
		return name;
	}
}
